<?php
namespace App\Services\Admin;

use Illuminate\Support\Facades\DB;

class FwCntService extends BaseService
{
    /**
     * 服务
     */

    //1文字，2图片，3视频，4评价
    protected $fwtypes = [
        1 => '文字', '图片', '视频', '评价',
    ];

    /**
     * 列表
     * @param array $pages【start起始页，limit每页记录数】
     * @param array $pas【type】
     */
    public function getIndex($pages, $pas)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbFwCnt)->where('del', 1)->where('fuwu_id', $pas['fwid']);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])->get();
        if (!count($res)) {
            return $this->toback(-2, 'no data');
        }
        $types = $this->fwtypes;
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $type_name = array_key_exists($v['type'], $types) ? $types[$v['type']] : '';
            if (in_array($v['type'], [2, 3])) {
                $cnt = file_exists($v['cnt']) ? $v['cnt'] : '';
            } else {
                $cnt = $v['cnt'];
            }
            $arys[] = [
                'id' => $v['id'],
                'type' => $v['type'],
                'type_name' => $type_name,
                'cnt' => $cnt,
                'prefixUrl' => env('DOMAIN').'/',
                'lasttime' => $v['uptime'],
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 新增
     * @param array $pas
     */
    public function add($pas)
    {
        $pas['uptime'] = $pas['addtime'] = toDate();
        $res = $this->dbConn($this->dbFwCnt)->insertGetId($pas);
        if (!$res) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 修改
     * @param int $id
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbFwCnt)
            ->where('id', $id)
            ->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 删除
     * @param int $id
     */
    public function del($id)
    {
        $res = $this->dbConn($this->dbFwCnt)
            ->where('del', 1)
            ->where('id', $id)
            ->update(['del' => 2]);
        if (!$res) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}